package com.zlay.javafx.examples.common;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;

public class ExJsonUtils {
	
	private static Logger log = Logger.getLogger(ExJsonUtils.class);
	
	public static Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().setDateFormat("yyyy-MM-dd HH:mm:ss").serializeNulls().create();
	
	public static Object readJsonFile(String path, String key) throws UnsupportedEncodingException, FileNotFoundException {
		Map<String ,Object> map = readJsonFile(path);
		if(map!=null&&map.size()>0) {
			return map.get(key);
		}
		return null;
	}
	
	public static Map<String ,Object> readJsonFile(String path) throws UnsupportedEncodingException, FileNotFoundException {
		JsonReader reader = null;
		try {
			File file = new File(path);
			if(!file.exists()) {
				return new HashMap<String, Object>();
			}
			reader = new JsonReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(file)), "UTF-8"));
			Map<String ,Object> map = gson.fromJson(reader, Map.class);
			return map;
		} finally {
			if(reader!=null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
					log.error("reader关闭出错!");
				}
			}
		}
	}
	
	/**
	 * 
	 * @param map
	 * @param path
	 * @param append true续写  false重头开始写覆盖已存在
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 */
	public static boolean writeJsonFile(Map<String ,Object> map, String path , boolean append) throws UnsupportedEncodingException, FileNotFoundException {
		PrintWriter printWriter = null;
		try {
			String str = gson.toJson(map);
			final String filePath = path.substring(0, path.lastIndexOf("/") + 1);
			new File(filePath).mkdirs();
			printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path, append), "UTF-8")));
			printWriter.write(str);
			printWriter.flush();
			return true;
		} finally {
			if (printWriter != null) {
				printWriter.close();
			}
		}
	}
	
	//默认为 文件已存在则覆盖
	public static boolean writeJsonFile(Map<String ,Object> map, String path) throws UnsupportedEncodingException, FileNotFoundException {
		return writeJsonFile(map, path, false);
	}
}
